import requests
from requests import utils
import threading
import json
import qrcode
import pygame
import os
import logging
import time

global COOKIE_DIRECT

def getLoginUrl():
    '''
    访问bilibili登录接口获取二维码信息
    :return:
    '''
    url = "https://passport.bilibili.com/qrcode/getLoginUrl"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    info = json.loads(response.text)
    return info["data"]["url"], info["data"]["oauthKey"]


def checkLogin(cookie):
    '''
    检测当前账号是否登录方法
    :param cookie: 用来登录的cookie
    :return:
    '''
    url = "https://api.bilibili.com/x/web-interface/nav"
    payload = ''
    headers = {
        'cookie': cookie,
    }
    response = requests.request("GET", url, headers=headers, data=payload)
    # print(response.text)
    info = json.loads(response.text)
    if info["code"] == -101:
        return False
    else:
        return True


def createQrcode(context):
    '''
    根据返回的内容创建登录用二维码图片
    :param context:
    :return:
    '''
    img = qrcode.make(context)
    if not os.path.exists("./temp/Qrcode"):
        logging.info("创建目录:" + "./temp/Qrcode")
        os.makedirs("./temp/Qrcode")
    with open('./temp/Qrcode/qrcode.png', 'wb') as f:
        img.save(f)


def checkScan(oauthKey):
    '''
    检查二维码是否被扫描
    :param oauthKey:
    :return:
    '''
    url = "https://passport.bilibili.com/qrcode/getLoginInfo"
    payload = 'oauthKey=' + oauthKey + '&gourl=https%3A%2F%2Fwww.bilibili.com%2Fv%2Fdouga%2F%3Fspm_id_from%3D333.6.b_7072696d6172794368616e6e656c4d656e75.1'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    info = json.loads(response.text)
    if info["status"] is False:
        return None
    elif info["status"] is True:
        cookiesDict = requests.utils.dict_from_cookiejar(response.cookies)
        return cookiesDict
    else:
        logging.error("无法扫描oauthkey！")
        return None


def checkScan_thread(oauthKey):
    '''
    检查二维码扫描线程方法
    :param oauthKey:
    :return:
    '''
    while True:
        time.sleep(2)
        result = checkScan(oauthKey)
        if result is not None:
            global COOKIE_DIRECT
            COOKIE_DIRECT = result
            return


def cookie2Str(cookiesDict):
    '''
    cookie转字符串方法
    :param cookiesDict:
    :return:
    '''
    cookieStr = ""
    for key in cookiesDict:
        cookieStr += (key+"="+cookiesDict[key]+"; ")
    return cookieStr


def viewQrcode(oauthKey):
    '''
    使用pygame显示二维码方法
    :param oauthKey:
    :return:
    '''
    pygame.init()  # 初始化pygame
    size = width, height = 400, 400  # 设置窗口大小
    screen = pygame.display.set_mode(size)  # 显示窗口
    pygame.display.set_caption('请用Bilibili客户端扫码登录！')
    qrCode = pygame.image.load('./temp/Qrcode/qrcode.png')  # 加载图片
    qrCode = pygame.transform.scale(qrCode, (400, 400))
    qrcode_rect = qrCode.get_rect()  # 获取矩形区域

    # 扫描标志
    global COOKIE_DIRECT
    COOKIE_DIRECT = None
    # 创建检测扫描二维码线程
    t = threading.Thread(target=checkScan_thread, kwargs={'oauthKey': oauthKey})
    t.setDaemon(True)
    t.start()
    # _thread.start_new_thread(checkScan_thread, (oauthKey,))

    while True:  # 死循环确保窗口一直显示
        for event in pygame.event.get():  # 遍历所有事件
            if event.type == pygame.QUIT:  # 如果单击关闭窗口，则退出
                pygame.quit()  # 退出pygame
                return 0
        screen.blit(qrCode, qrcode_rect)  # 将图片画到窗口上
        pygame.display.flip()  # 更新全部显示
        if COOKIE_DIRECT is not None:
            pygame.quit()  # 退出pygame
            return COOKIE_DIRECT
